Ext.onReady(function() {

    Ext.QuickTips.init();// 浮动信息提示

    //树状结构
    var treePanel = new Ext.tree.TreePanel({
        el : 'tree-panel',// 将树形添加到一个指定的div中,非常重要！
        title : '机构管理工作台',
        width :200,
        height : 480,
        split : true,
        lines:true,
        autoHeight : false,
        containerScroll : true,// 是否支持滚动条
        rootVisible : true, // 是否隐藏根节点,很多情况下，我们选择隐藏根节点增加美观性
        collapsible:false,
        collapsed:false,
        collapseFirst:true,
        titleCollapse:true,
        border : false,
        //border : true, // 边框

        animate : true, // 动画效果

        loader : loader,
            // 树加载
        listeners:{ 
        	render:function(tree){ 
        		treePanel.el.on('click',function(e){ 
				e.stopPropagation(); }) ;
			} 
		} 

        });

var loader=new Ext.tree.TreeLoader({dataUrl:'system/showOrgTree.do'});

var treeRoot=new Ext.tree.AsyncTreeNode
    ({
     id:"0", 
     leaf:false,
     loader: loader,
     text:"清远农商行总行",
     expandable:true,
     expanded:true 
 });         

treePanel.setRootNode(treeRoot);
treePanel.render();

var treeClick = function(node,e)
    {
	 var flag = false; 
	  if(node.attributes.leaf)
      {
          if(node.isLeaf())
          {
        	  e.stopEvent();
        	  flag = true;
          }
         
      }
		Ext.Ajax.request({
			url:'system/loadTreeFromParent.do',
			params : { orgId: node.id, isLeaf: flag},
			method:'POST',
			   success:function(response){
				   grid.store.reload(); 
				   treePanel.root.reload();
			  },failure:function(){
			    Ext.MessageBox.alert("请求异常！");
			  }
			});
      
    };
    treePanel.on("click",treeClick); 
	
	//机构列表

	var record_start = 0; 
	var sm = new Ext.grid.CheckboxSelectionModel();
	var cm=new Ext.grid.ColumnModel([ 
	sm,
	new Ext.grid.RowNumberer({header: "编号",
	width:40, 
	renderer:function(value,metadata,record,rowIndex){ 
	return record_start + 1 + rowIndex; 
	} 
	}),
	{header:'机构代码',dataIndex:'orgId',width:120,hidden:true},
	{header:'机构名称',dataIndex:'orgname',width:120},
	{header:'机构代码',dataIndex:'bankid',width:100},
	{header:'核心机构代码',dataIndex:'orgCode',width:100},
	{header:'机构地址',dataIndex:'orgadd',width:100},
	{header:'联系电话',dataIndex:'orgtel',width:100},
	{header:'更新日期',dataIndex:'updateDate',width:100}
	]); 
	var ds=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'system/listOrg.do',
	method:'POST'
	}), 
	reader:new Ext.data.JsonReader({ 
	totalProperty:'total',  
	root:'resultData'},[
	{name:'orgId'}, 
	{name:'orgname'}, 
	{name:'bankid'}, 
	{name:'orgcode'},  
	{name:'orgadd'},
	{name:'orgtel'},
	{name:'updateDate'},
	]) 
	});

	var grid=new Ext.grid.GridPanel({ 
		id:'myCustomers',
		renderTo:"list", 
		stripeRows:true,//斑马线效果
		title:"机构列表", 
		height:500, 
		cm:cm,
		store: ds, 
		loadMask: { msg: "加载中..." }, 
		viewConfig: {   
		                            forceFit:true   
		            },   
		            bbar: new Ext.PagingToolbar({   
		                pageSize: 20,   
		                store: ds,   
		                displayInfo: true,   
		                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
		                emptyMsg: "没有数据" ,
		                doLoad : function(start){ 
		   record_start = start; 
		var o = {}, pn = this.getParams(); 
		          o[pn.start] = start; 
		          o[pn.limit] = this.pageSize; 
		this.store.load({params:o}); 
		     }  
		            }),
		 tbar: [
		 {text:'新增',handler: startPD},
		 '-',
		 {text:'查看/编辑',handler: PDDetail},
		 '-',
		 {text:'删除',handler: deleteOrg},
		 ]              
		});
		ds.load({params:{start:0,limit:20}}); 
		
		

		//新增客户表单
		addForm = new Ext.form.FormPanel({ 
		id: 'addForm', 
		width: 480, 
		height: 200, 
		//样式 
		bodyStyle: 'margin:auto;padding:auto;', 
		frame: true, 
		xtype: 'filedset', 
		labelWidth: 100, 
		items: 
		[ { xtype: 'fieldset',  
		collapsible: true, 
		autoHeight: true, 
		autoWidth: true, 
		items: 
		[ 
		{ layout : "form",
		           items : [{
		        	   xtype: 'textfield',
		        	   id: 'orgname', 
		        	   name: 'orgname', 
		        	   fieldLabel: '机构名称',
		        	   allowBlank : false,
		        	   blankText:'请输入机构名称',
		        	   width: 250
		}]},
		{ layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'bankid', 
	        	   name: 'bankid', 
	        	   fieldLabel: '机构代码',
	        	   width: 250
	     }]},
		 { layout : "form",
		           items : [{
					xtype: 'combo',
					id: 'orgCode',
					//name: 'exposureType', 
					fieldLabel: '上级机构', 
					store:new Ext.data.SimpleStore({fields:['id', 'text'],data:[[]]}), 
					displayField: 'id',
					valueField: 'text',
					hiddenName: 'orgCode',
		            editable:false, 
		            mode: 'local', 
		            triggerAction:'all', 
		            frame:true,
		            border:true,
		            width:250,
		            tpl: '<div id="treePanel" style="height:180px;width:240px;"></div>', //html代码           
		            //autoWidth:true,
		            //autoHeight:true, 
		            emptyText:'请选择上级机构...',
		            resizable:true
		}]},
		
		 { layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'orgadd', 
	        	   name: 'orgadd', 
	        	   fieldLabel: '机构地址',
	        	   width: 250
	     }]},
		
		{ layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'orgtel', 
	        	   name: 'orgtel', 
	        	   fieldLabel: '联系电话',
	        	   width: 250
	     }]},
	     
	    
	     
	     
		]}]});
		
		var tree = new Ext.tree.TreePanel
        ({ 
            animate:true,
            titleCollapse:true,
            root:root,
            singleExpand:false,
            iconCls:"icon-tree",
            autoLoad:false,
            allowDomMove:true,
            frame:true,
            collapsible:false,
            collapsed:false,
            collapseFirst:true,
            border:false,
            listeners:{ 
            	render:function(tree){ 
            		tree.el.on('click',function(e){ 
					e.stopPropagation(); }) ;
				} 
			} 
});

var loader=new Ext.tree.TreeLoader({dataUrl:'system/showOrgTree.do'});

var root=new Ext.tree.AsyncTreeNode
        ({
         id:"0", 
         leaf:false,
         loader: loader,
         text:"清远农商行总行",
         expandable:true,
         expanded:true 
     });         

tree.setRootNode(root);

var comboTree =  Ext.getCmp('orgCode');      
var orgCode = "";
comboTree.on('expand',function(){tree.render('treePanel');});

var tree_click = function(node,e)
        {
			 e.stopEvent();   //非叶子节点则不触发
		     comboTree.setValue(node.id);  //设置option值
		     comboTree.setRawValue(node.text);
		     //comboTree.hiddenField.value = node.id;  
		 	comboTree.collapse();   //隐藏option列表
		 	//alert(comboTree.value);
		// 	alert(comboTree.getValue());
		// 	alert(comboTree.getRawValue());
		 	//alert(comboTree.value);
		 	orgCode = comboTree.value;
        };
tree.on("click",tree_click);  
		
		
		//新增用户窗口 
		addWin = new Ext.Window({ 
		id: 'addWin', 
		title: '添加机构', 
		width: 500, 
		height: 250, 
		//背景遮罩 
		modal: true, 
		//重置大小 
		resizable: false, 
		//当关闭按钮被点击时执行的动作 
		closeAction: 'hide', 
		plain: true, 
		buttonAlign: 'right', 
		items:addForm, 
		buttons: 
		[  
		{ text: '保存', id: 'btnSubmit' } ,
		{ text: '关闭', handler: function() { Ext.getCmp('addWin').hide(); } }

		] 
		});
		
		function startPD(){
			Ext.getCmp('addForm').form.reset();
			Ext.getCmp("addWin").buttons[0].handler = addFunction; 
			Ext.getCmp("addWin").show();
		}

		function addFunction() {
			if(addForm.form.isValid()){
			 addForm.form.doAction('submit', { 
		                    url : 'system/addOrg.do', 
		                    method : 'post',   
		                    params : { orgCodeValue: orgCode},
		                    success : function() { 		                       
		                    	grid.store.reload();
		                    	 treePanel.root.reload();
		                    	Ext.Msg.alert('提示', '保存成功！'); 
		 
		                       }, 
		                        failure : function(form, action) { 
		                           Ext.Msg.alert('提示', '保存未成功！'); 
		                        } 
		                    });  
		                    }
		}


		function PDDetail(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要查看的项！"); 
				}
				else{
						var orgId = grid.getSelectionModel().getSelections()[0].data.orgId;
					
					Ext.getCmp('addForm').form.reset(); 
					Ext.getCmp("addWin").buttons[0].handler = editAddressFunction; 
					
				Ext.Ajax.request({
				url:'system/getOrg.do',
				params : { orgId: grid.getSelectionModel().getSelections()[0].data.orgId},
				method:'POST',
				   success:function(response){
				 var addJSON = Ext.util.JSON.decode(response.responseText);

				 	Ext.getCmp("addWin").show();
				  	Ext.getCmp("orgname").setValue(addJSON.orgname);
				  	Ext.getCmp("bankid").setValue(addJSON.bankid);
				  	Ext.getCmp("orgCode").setValue(addJSON.orgCode);
				   	Ext.getCmp("orgadd").setValue(addJSON.orgadd);
				   	Ext.getCmp("orgtel").setValue(addJSON.orgtel);		
				   	
				  },failure:function(){
				    Ext.MessageBox.alert("请求异常！");
				  }
				}); 
				}
		}
		
		//编辑
		function editAddressFunction(){
			
			var addForm = Ext.getCmp("addForm");
		if(addForm.form.isValid()){
			 addForm.form.doAction('submit', { 

		                    url : 'system/editOrg.do', 
		                    params : { orgId: grid.getSelectionModel().getSelections()[0].data.orgId,orgCodeValue: orgCode},
		                    method : 'post', 
		 
		                       
		                       success : function() { 

		                       
		                       grid.store.reload();
		                       treePanel.root.reload();
		                       Ext.Msg.alert('提示', '编辑成功！'); 
		 
		                       }, 
		                        failure : function(form, action) { 

		                           Ext.Msg.alert('提示', '编辑失败！'); 
		 
		                        } 
		                    }); 
		                    }
		}

		
		function deleteOrg(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要操作的项！"); 
			}
			else{
				var rows=grid.getSelectionModel().getSelections(); 
				//alert(selectedSerialNo);
				//window.location.href="rating/showHistoryPDList.do?custId="+selectedCustId;
				Ext.Msg.confirm("Confirm",'确实要删除所选中项吗？',function(bool){
					if(bool=='yes'){
						var selectedSerialNo = '';
					     for(var i=0;i <rows.length;i++){ 					      
					    	  selectedSerialNo = grid.getSelectionModel().getSelections()[i].data.orgId; 					   
					    	  Ext.Ajax.request({
								  url:'system/deleteOrg.do',
								  params : {orgId : selectedSerialNo},
								  method:'POST',
								  success:function(){
								  // Ext.MessageBox.alert("提示","删除成功！");
								  //  grid.store.reload(); 
								   treePanel.root.reload();
								  },failure:function(){
								   // Ext.MessageBox.alert("提示", "删除失败！"); 
								  }
							});
					     }
					     
					     grid.store.reload();
					     Ext.MessageBox.alert("提示","删除成功！");
					     
						return true;
					}
					else{
						return false;	
					}
				}); 
				
			}
		}
});